<html>
<head><title>CS143 Project1B</title></head>
<body>
<?php
//grab input
$query = $_GET['query'];
?>
Type an SQL query in the following box:
<p>
<form action="query.php" method="GET">
<textarea name="query" cols="60" rows="8"><?php echo $query; ?></textarea>
<input type="submit" value="Submit" />
</form>
</p>
</body>
</html>

<?php

if (!$query)
	exit(0);

//Establish database connection
$con = mysql_connect("localhost", "cs143", "") or die("Connection failed");
if ( ! mysql_select_db("CS143", $con)) {
	$err = mysql_error($con);
	die("Failed to select database: $err<br/>");
}

//Issue the query that the user supplied
$result = mysql_query($query, $con);

if ($result == FALSE) {
	$err = mysql_error($con);
	die("Query failed: $err");
}

//Print results
echo '<b>Results from MySQL:</b><br/>';
echo '<table border="1" bgcolor="white"><tr>';

$nfields = mysql_num_fields($result);
for ($i = 0; $i < $nfields; $i++) {
	$field = mysql_fetch_field($result, $i);
	echo '<th>' . $field->name . '</th>';
}	
echo '</tr>';

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
	
	echo '<tr>';
	for ($i = 0; $i < $nfields; $i++) {
		$field = mysql_fetch_field($result, $i);
		$value = $row[$field->name];
		if ($value == NULL)
			$value = 'NULL';
		echo '<td>' . $value . '</td>';
	}
	echo '<tr/>';
}

mysql_close($con);

?>
